# -*- coding: utf-8 -*-

import DBLink.dbHelp
import Encapsulation.Complete

complete=Encapsulation.Complete
dbHelp = DBLink.dbHelp

def _api_department_type_view_num(_request):
    """
             API /api/department.type.view.num

            功能：试卷管理 部分-- 根据（部门 + 岗位） 提取题目后按题型分类显示数量(未组卷)
            编写：朱盼盼
            :param _request: 传入参数 = {{"RequestBaseHeader":{"SeesionKey":" ","TimeSpan":" "},"JobID":5,"DepartmentID":2}
            :param _request["DepartmentID"]:部门ＩＤ
            :param _request["JobID"]:职位ID
            :param _request["RowNum"]:总数
            :param _request["TBTypeNumView"]:字典类型
                            :param _request["Num"]:题目类型数量
                            :param _request["ItemType"]:题目类型
            :return: _respon 返回信息 = {"RowNum": 4, "ErrorInfo": {"ErrorCode": 0, "ErrorMsg": ""}, "TBTypeNumView": [{"Num": 1, "ItemType": "判断题"}, {"Num": 1, "ItemType": "单选题"}, {"Num": 3, "ItemType": "多选题"}, {"Num": 1, "ItemType": "简答题"}], "IsError": false, "ReturnValue": true}
            """
    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": "","TBTypeNumView": [{"Num": 0, "ItemType": "判断题"}, {"Num": 0, "ItemType": "单选题"}, {"Num": 0, "ItemType": "多选题"}, {"Num": 0, "ItemType": "主观题"}, {"Num": 0, "ItemType": "操作题"}]}
    strSqlSelect = """
      select COUNT(T.ItemType) AS Num,T.ItemType
        from itema T
        WHere T.DepartmentID='""" + str(_request["DepartmentID"]) + """'
        AND T.JobID='""" + str(_request["JobID"]) + """'
        AND T.IsDelete=0
        GROUP BY T.ItemType
    """
    selectObj = dbHelp.Select(strSqlSelect)
    _respon["ErrorInfo"]["ErrorCode"] = selectObj["ErrorCode"]
    _respon["ErrorInfo"]["ErrorMsg"] = selectObj["ErrorMsg"]
    _respon["IsError"] = selectObj["IsError"]
    _respon["ReturnValue"] = selectObj["ReturnValue"]
    if selectObj["ReturnValue"] == True:
        _respon["RowNum"] = len(selectObj["Value"])
        _respon["TBTypeNumView"] = selectObj["Value"]
    else:
        # 没有查询到数据 , 上一层已经提交了错误信息
        _respon["RowNum"] =0

    return _respon

#根据条件组卷，生成试卷
def _api_testpaper_generate_paper(_request):
    """
    API:/api/testpaper.generate.paper

    功能：根据条件组卷，生成试卷
    编写：张耀文
    :param _request = {"RequestBaseHeader":{"SeesionKey":" ","TimeSpan":" "},"Examiner":"zyw","Examinee":"zyw",
                        "DepartmentID":1,"JobID":2,
                        "ItemTables":[
                        {"ItemType":"单选","ItemScore":5,"ItemNum":6},
                        {"ItemType":"多选","ItemScore":5,"ItemNum":6},
                        {"ItemType":"判断","ItemScore":5,"ItemNum":6},
                        {"ItemType":"问答","ItemScore":5,"ItemNum":6},
                        {"ItemType":"操作","ItemScore":5,"ItemNum":6}]}
    :param _request["Examiner"]:主考人(string)
    :param _request["Examinee"]:参考人(string)
    :param _request["DepartmentID"]:部门ID(int)
    :param _request["JobID"]:岗位ID(int)
    :param _request["ItemTables"]:选题列表(list)
    :param _request["ItemType"]:题型(string)
    :param _request["ItemScore"]:试题分值(int)
    :param _request["ItemNum"]:本题型题目数(int)  (ItemNum没有请填0)
    :param _request["operationUserID"]:操作账号
    :param _request["Remarks"]:备注

    :return: _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": "","TPCode":3}
    :return: _respon["TPCode"]: 试卷编码(int)
    """

    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": ""}

    #获取主表试卷ID
    objIdReturnTPCode = dbHelp.GetNewids("testpapera")
    if objIdReturnTPCode["Value"] == 0:                                                 #失败
        _respon["IsError"] = objIdReturnTPCode["IsError"]
        _respon["ErrorInfo"]["ErrorCode"] = objIdReturnTPCode["ErrorCode"]
        _respon["ErrorInfo"]["ErrorMsg"] = objIdReturnTPCode["ErrorMsg"]
        _respon["ReturnValue"] = objIdReturnTPCode["ReturnValue"]

    else:
        if objIdReturnTPCode["ReturnValue"]:                                            #成功
            TPCodeOfItem = objIdReturnTPCode["Value"]                                   #试卷ID
                                                                                        #获取主表试卷ID成功,执行新增主表操作
            strInPaperASql = """
                    INSERT INTO testpapera
                    (TPCode,DateBuild,Examiner,Examinee,DepartmentID,JobID,IsDelete,Remarks)
                    VALUES(
                    """ + TPCodeOfItem + """
                    ,DATE_FORMAT(now(),'%Y-%m-%d %H:%i:%s')
                    ,'""" + str(_request["Examiner"]) + """'
                    ,'""" + str(_request["Examinee"]) + """'
                    ,'""" + str(_request["DepartmentID"]) + """'
                    ,'""" + str(_request["JobID"]) + """'
                    ,0
                    ,'""" + str(_request["Remarks"]) + """'
                    )
            """
            objReturnInsPA = dbHelp.Exec(strInPaperASql)
            _respon["IsError"] = objReturnInsPA["IsError"]
            _respon["ErrorInfo"]["ErrorCode"] = objReturnInsPA["ErrorCode"]
            _respon["ErrorInfo"]["ErrorMsg"] = objReturnInsPA["ErrorMsg"]
            _respon["ReturnValue"] = objReturnInsPA["ReturnValue"]
            if objReturnInsPA["ReturnValue"]:                                           #插入主表成功,执行后续操作:
                dbHelp.FF_update_table_state_create('testpapera', _request['operationUserID'], 'TPCode',
                                                    TPCodeOfItem)
                _respon["TPCode"] = TPCodeOfItem                                #返回试卷ID

                                                                                        #循环题型种类
                for x in range(len(_request["ItemTables"])):
                    TypeOfItem = _request["ItemTables"][x]["ItemType"]                  #题目类型
                    NumOfThisTypeItem = _request["ItemTables"][x]["ItemNum"]            #此类数量
                    ScoreOfItem = _request["ItemTables"][x]["ItemScore"]                #此类分值
                    # print TypeOfItem,'有',NumOfThisTypeItem,'题,每题',ScoreOfItem,'分'

                    if NumOfThisTypeItem>0:                                             #如果有题
                                                                                        #随机抽这个题型题数的题
                        selectItemSql = """
                                        SELECT T1.ItemCode
                                        FROM itema T1
                                        WHERE T1.ItemType = '""" + str(TypeOfItem) + """'
                                        AND   T1.DepartmentID = '""" + str(_request["DepartmentID"]) + """'
                                        AND   T1.JobID = '""" + str(_request["JobID"]) + """'
                                        AND T1.IsDelete = 0
                                        ORDER BY RAND()
                                        LIMIT """ + str(NumOfThisTypeItem) + """
                        """
                        objReturnItems = dbHelp.Select(selectItemSql)
                        if objReturnItems["ReturnValue"] != True:
                            _respon["IsError"] = objReturnItems["IsError"]
                            _respon["ErrorInfo"]["ErrorCode"] = objReturnItems["ErrorCode"]
                            _respon["ErrorInfo"]["ErrorMsg"] = TypeOfItem,'不足',NumOfThisTypeItem,'道'
                            _respon["ReturnValue"] = objReturnItems["ReturnValue"]

                        if objReturnItems["ReturnValue"]:                               #抽题成功
                            for x1 in objReturnItems["Value"]:                          #循环取出的题目ID:x1["ItemCode"]
                                ItemCode = x1["ItemCode"]                               #抽出来的题号,type-->int
                                # print '抽出来的',TypeOfItem,'题号',x1["ItemCode"],'--->',type(x1["ItemCode"])

                                #执行从表插入
                                objIdReturnTPBCode = dbHelp.GetNewids("testpaperb")
                                if objIdReturnTPBCode["Value"] == 0:
                                    _respon["IsError"] = objIdReturnTPBCode["IsError"]
                                    _respon["ErrorInfo"]["ErrorCode"] = objIdReturnTPBCode["ErrorCode"]
                                    _respon["ErrorInfo"]["ErrorMsg"] = objIdReturnTPBCode["ErrorMsg"]
                                    _respon["ReturnValue"] = objIdReturnTPBCode["ReturnValue"]
                                else:
                                    if objIdReturnTPBCode["ReturnValue"]:                   #从表GetNewIDs成功
                                        # 获取从表试卷ID成功,执行新增从表操作
                                        # print ' 获取从表试卷ID成功'
                                        # print type(ScoreOfItem)
                                        insertItemSql = """
                                            INSERT INTO testpaperb
                                            (TPBCode,TPCode,ItemCode,ItemScore,IsDelete)
                                            VALUES(
                                              """ + objIdReturnTPBCode["Value"] + """
                                              ,""" + TPCodeOfItem + """
                                              ,'""" + str(ItemCode) + """'
                                              ,'""" + str(ScoreOfItem) + """'
                                              ,'0'
                                            )
                                        """
                                        objReturnInsPB = dbHelp.Exec(insertItemSql)
                                        # print objReturnInsPB
                                        _respon["IsError"] = objReturnInsPB["IsError"]
                                        _respon["ErrorInfo"]["ErrorCode"] = objReturnInsPB["ErrorCode"]
                                        _respon["ErrorInfo"]["ErrorMsg"] = objReturnInsPB["ErrorMsg"]
                                        _respon["ReturnValue"] = objReturnInsPB["ReturnValue"]
                                        if objReturnInsPB["ReturnValue"]:
                                            dbHelp.FF_update_table_state_create('testpaperb',
                                                                                _request['operationUserID'], 'TPBCode',
                                                                                objIdReturnTPBCode["Value"])

                                                                                                            #完结撒花 ***
    return _respon

#在线答题部分，保存考生答案，客观题顺便计分
def _api_testpaper_do_submit(_request):
    """
         API:/api/testpaper.do.submit

        功能：在线答题部分，保存考生答案，客观题顺便计分
        编写：张耀文
        :param _request: 传入参数 = {"RequestBaseHeader":{"SeesionKey":" ","TimeSpan":" "},"InAnswerList":{"1":"A","2":"ABC","3":"封装,继承,多态"},"TPCode":1}
        :param _request["TPCode"]:试卷编码
        :param _request["InAnswerList"]:答案列表
        :param _request["operationUserID"]:操作账号

        :return: _respon 返回信息 = {"ErrorInfo": {"ErrorCode": 0, "ErrorMsg": ""}, "IsError": false, "ReturnValue": true","PartAScore": 3,}
        """

    #初始化返回信息
    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": "","PartAScore": 0}

    #取出答案列表中的试题编号并循环插入数据表中的每行的答题内容
    for x in _request["InAnswerList"]:
        # print x,'-->',_request["InAnswerList"][x]
        selectTypeSql = """
            SELECT T1.ItemType
            FROM itema T1
            WHERE T1.ItemCode = '""" + x + """'
        """
        objReturnType = dbHelp.Select(selectTypeSql)
        if objReturnType["ReturnValue"]:
            Type = objReturnType["Value"][0]["ItemType"]
            if Type=='多选':
                updateSql = """
                            UPDATE testpaperb T1
                            SET T1.InAnswer = '""" + str("".join(sorted(_request["InAnswerList"][x]))) + """'
                            WHERE T1.TPCode = '""" + str(_request["TPCode"]) + """'
                            AND T1.ItemCode = '""" + x + """'
                            AND T1.IsDelete = '0'
                        """
            else:
                updateSql = """
                    UPDATE testpaperb T1
                    SET T1.InAnswer = '""" + str(_request["InAnswerList"][x]) + """'
                    WHERE T1.TPCode = '""" + str(_request["TPCode"]) + """'
                    AND T1.ItemCode = '""" + x + """'
                    AND T1.IsDelete = '0'
                """
        objReturn = dbHelp.Exec(updateSql)
        _respon["ErrorInfo"]["ErrorCode"] = objReturn["ErrorCode"]
        _respon["ErrorInfo"]["ErrorMsg"] = objReturn["ErrorMsg"]
        _respon["IsError"] = objReturn["IsError"]
        _respon["ReturnValue"] = objReturn["ReturnValue"]

    # print _respon["ReturnValue"]

    #如果答题内容插入成功,计算客观题总分
    if _respon["ReturnValue"] == True:
        dbHelp.FF_update_table_state_update('testpaperb', _request['operationUserID'], 'TPCode',
                                            str(_request["TPCode"]))
        selectScoreSql = """
                    SELECT SUM(ItemScore) AS PartAScore
                    FROM testpaperb T1
                    LEFT JOIN itema T2
                    ON T1.ItemCode = T2.ItemCode
                    WHERE T1.InAnswer = T2.ItemAnswer
                    AND T2.ItemType IN ('单选','多选','判断')
                    AND T1.TPCode = '""" + str(_request["TPCode"]) + """'
        """
        objReturnB = dbHelp.Select(selectScoreSql)
        # _respon["ErrorInfo"]["ErrorCode"] = objReturnB["ErrorCode"]
        # _respon["ErrorInfo"]["ErrorMsg"] = objReturnB["ErrorMsg"]
        # _respon["IsError"] = objReturnB["IsError"]

        #如果计算值不为空,则返回PartAScore
        if objReturnB["Value"][0]["PartAScore"] != None:
            _respon["PartAScore"] = int(objReturnB["Value"][0]["PartAScore"])

            # 更新试卷主表PartAScore
            updateScoreSql = """
                            UPDATE testpapera T1
                            SET T1.PartAScore = '""" + str(_respon["PartAScore"]) + """"'
                            WHERE T1.TPCode = '""" + str(_request["TPCode"]) + """'
                            """
            objReturnC = dbHelp.Exec(updateScoreSql)
            if objReturnC["ReturnValue"]:
                dbHelp.FF_update_table_state_update('testpapera', _request['operationUserID'], 'TPCode',
                                                    str(_request["TPCode"]))
    return _respon

#考官评分信息保存
def _api_testpaper_check_submit(_request):
    """
             API:/api/testpaper.check.submit

            功能：考官评分信息保存
            编写：张耀文
            :param _request: 传入参数 = {"RequestBaseHeader":{"SeesionKey":" ","TimeSpan":" "},"InScoreList":{"11":"10","12":"10","13":"10"},"TPCode":2}
            :param _request["TPCode"]:试卷编码
            :param _request["InScoreList"]:评分列表:{"题号":"分数","题号":"分数"}
            :param _request["operationUserID"]:操作账号

            :return: _respon 返回信息 = {"ErrorInfo": {"ErrorCode": 0, "ErrorMsg": ""}, "IsError": false, "ReturnValue": true","PartBScore": 3,}
            """

    # 初始化返回信息
    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": "","PartBScore": 0}

    # 取出评分列表中的试题编号并循环插入数据表中的每行的评分
    for x in _request["InScoreList"]:
        # print x,'-->',_request["InAnswerList"][x]
        updateSql = """
                UPDATE testpaperb T1
                SET T1.Grade = '""" + str(_request["InScoreList"][x]) + """',
                    update_user = '""" + str(_request['operationUserID']) + """',
                    update_time = NOW()
                WHERE T1.TPCode = '""" + str(_request["TPCode"]) + """'
                AND T1.ItemCode = '""" + x + """'
                AND T1.IsDelete = '0'
            """
        objReturn = dbHelp.Exec(updateSql)
        _respon["ErrorInfo"]["ErrorCode"] = objReturn["ErrorCode"]
        _respon["ErrorInfo"]["ErrorMsg"] = objReturn["ErrorMsg"]
        _respon["IsError"] = objReturn["IsError"]
        _respon["ReturnValue"] = objReturn["ReturnValue"]
    # print _respon["ReturnValue"]

    # 如果评分插入成功,计算主观题总分
    if _respon["ReturnValue"] == True:
        selectScoreSql = """
                        SELECT SUM(Grade) AS PartBScore
                        FROM testpaperb T1
                        LEFT JOIN itema T2
                        ON T1.ItemCode = T2.ItemCode
                        WHERE T2.ItemType NOT IN ('单选','多选','判断')
                        AND T1.TPCode = '""" + str(_request["TPCode"]) + """'
            """
        objReturnB = dbHelp.Select(selectScoreSql)
        # _respon["ErrorInfo"]["ErrorCode"] = objReturnB["ErrorCode"]
        # _respon["ErrorInfo"]["ErrorMsg"] = objReturnB["ErrorMsg"]
        # _respon["IsError"] = objReturnB["IsError"]

        # 如果计算值不为空,则返回PartBScore
        if objReturnB["Value"][0]["PartBScore"] != None:
            _respon["PartBScore"] = int(objReturnB["Value"][0]["PartBScore"])

            # 更新试卷主表PartBScore
            updateScoreSql = """
                    UPDATE testpapera T1
                    SET T1.PartBScore = '""" + str(_respon["PartBScore"]) + """"'
                    WHERE T1.TPCode = '""" + str(_request["TPCode"]) + """'
                    """
            objReturnC = dbHelp.Exec(updateScoreSql)
            if objReturnC["ReturnValue"]:
                dbHelp.FF_update_table_state_update('testpapera', _request['operationUserID'], 'TPCode',
                                                    str(_request["TPCode"]))

    return _respon

#试卷查询 - 包含题目、考生答案、参考答案
def _api_testpaper_view_questionAndAnswer(_request):
    """
        API:/api/testpaper.view.questionAndAnswer

        功能：试卷查询 - 包含题目、考生答案、参考答案
        编写：张耀文
        :param _request = {"RequestBaseHeader":{"SeesionKey":" ","TimeSpan":" "},"TPCode":2,}
        :param _request["TPCode"]: 试卷编号 (int)
        :param _request["operationUserID"]:操作账号

        :return: _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": "","PartBScore": 3,
                    "paperTable":[
                    {"ItemType": "主观", "ItemCode": 1, "ItemQuestion": "java三大特性? ", "ItemScore": 5, "ItemAnswer": "封装，继承，多态 （必须答对）", "InAnswer": "封装，继承，多态 "},
                    {"ItemType": "判断", "ItemCode": 16, "ItemQuestion": null, "ItemScore": 4, "ItemAnswer": null, "InAnswer": "AC"},
                    {"ItemType": "单选", "ItemCode": 11, "ItemQuestion": "Java的优势", "ItemScore": 5, "ItemAnswer": "ACD", "InAnswer": "ACD"},
                    {"ItemType": "单选", "ItemCode": 12, "ItemQuestion": "Java的劣势", "ItemScore": 5, "ItemAnswer": "ACD", "InAnswer": "ACD"},
                    {"ItemType": "多选", "ItemCode": 13, "ItemQuestion": null, "ItemScore": 5, "ItemAnswer": "ABD", "InAnswer": "A"},
                    {"ItemType": "多选", "ItemCode": 14, "ItemQuestion": null, "ItemScore": 10, "ItemAnswer": null, "InAnswer": null},
                    {"ItemType": "多选", "ItemCode": 15, "ItemQuestion": null, "ItemScore": 30, "ItemAnswer": null, "InAnswer": null},
                    {"ItemType": "简答", "ItemCode": 21, "ItemQuestion": null, "ItemScore": 30, "ItemAnswer": null, "InAnswer": null}]}
        :return: _respon["paperTable"]:     试卷题目列表   (list)
        :return: _respon["ItemType"]        题目类型       (string)
        :return: _respon["ItemCode"]        题目编码       (int)
        :return: _respon["ItemQuestion"]    题目内容       (string)
        :return: _respon["ItemScore"]       题目分值       (int)
        :return: _respon["ItemAnswer"]      参考答案       (string)
        :return: _respon["InAnswer"]        考生答案       (string)
        :return: _respon["PartBScore"]      客观题总分
        """
    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": "","paperTable":"","PartBScore":"0"}
    strSelectSql = """
                SELECT T1.ItemCode,T2.ItemType,T2.ItemQuestion,T1.ItemScore,T1.InAnswer,T2.ItemAnswer,(T3.PartBScore+T3.PartAScore) AS PartBScore
                FROM testpaperb T1,itema T2,testpapera T3
                WHERE T1.TPCode = """ + str(_request["TPCode"]) + """
                AND T1.ItemCode = T2.ItemCode
                AND T1.TPCode = T3.TPCode
        """
    selectObjReturn = dbHelp.Select(strSelectSql)
    _respon["ErrorInfo"]["ErrorCode"] = selectObjReturn["ErrorCode"]
    _respon["ErrorInfo"]["ErrorMsg"] = selectObjReturn["ErrorMsg"]
    _respon["IsError"] = selectObjReturn["IsError"]
    _respon["ReturnValue"] = selectObjReturn["ReturnValue"]
    if selectObjReturn["ReturnValue"]:
        _respon["paperTable"] = selectObjReturn["Value"]
        _respon["PartBScore"] = int(selectObjReturn["Value"][0]["PartBScore"])
    return _respon

#考官评卷 - 包含题目、考生答案、参考答案
def _api_testpaper_view_questionAndAnswer_v2(_request):
    """
        API:/api/testpaper.view.questionAndAnswer.v2

        功能：考官评卷 - 包含题目、考生答案、参考答案(只显示主观题)
        编写：张耀文
        :param _request = {"RequestBaseHeader":{"SeesionKey":" ","TimeSpan":" "},"TPCode":2,}
        :param _request["TPCode"]: 试卷编号 (int)
        :param _request["operationUserID"]:操作账号

        :return: _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": "","PartBScore": 3,
                    "paperTable":[
                    {"ItemType": "主观", "ItemCode": 1, "ItemQuestion": "java三大特性? ", "ItemScore": 5, "ItemAnswer": "封装，继承，多态 （必须答对）", "InAnswer": "封装，继承，多态 "},
                    {"ItemType": "判断", "ItemCode": 16, "ItemQuestion": null, "ItemScore": 4, "ItemAnswer": null, "InAnswer": "AC"},
                    {"ItemType": "单选", "ItemCode": 11, "ItemQuestion": "Java的优势", "ItemScore": 5, "ItemAnswer": "ACD", "InAnswer": "ACD"},
                    {"ItemType": "单选", "ItemCode": 12, "ItemQuestion": "Java的劣势", "ItemScore": 5, "ItemAnswer": "ACD", "InAnswer": "ACD"},
                    {"ItemType": "多选", "ItemCode": 13, "ItemQuestion": null, "ItemScore": 5, "ItemAnswer": "ABD", "InAnswer": "A"},
                    {"ItemType": "多选", "ItemCode": 14, "ItemQuestion": null, "ItemScore": 10, "ItemAnswer": null, "InAnswer": null},
                    {"ItemType": "多选", "ItemCode": 15, "ItemQuestion": null, "ItemScore": 30, "ItemAnswer": null, "InAnswer": null},
                    {"ItemType": "简答", "ItemCode": 21, "ItemQuestion": null, "ItemScore": 30, "ItemAnswer": null, "InAnswer": null}]}
        :return: _respon["paperTable"]:     试卷题目列表   (list)
        :return: _respon["ItemType"]        题目类型       (string)
        :return: _respon["ItemCode"]        题目编码       (int)
        :return: _respon["ItemQuestion"]    题目内容       (string)
        :return: _respon["ItemScore"]       题目分值       (int)
        :return: _respon["ItemAnswer"]      参考答案       (string)
        :return: _respon["InAnswer"]        考生答案       (string)
        :return: _respon["PartBScore"]      客观题总分
        """
    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": "","paperTable":"","PartBScore":"0"}
    strSelectSql = """
                SELECT T1.ItemCode,T2.ItemType,T2.ItemQuestion,T1.ItemScore,T1.InAnswer,T2.ItemAnswer,T3.PartBScore
                FROM testpaperb T1,itema T2,testpapera T3
                WHERE T1.TPCode = """ + str(_request["TPCode"]) + """
                AND T1.ItemCode = T2.ItemCode
                AND T1.TPCode = T3.TPCode
                AND T2.ItemType IN ('主观','操作')
        """
    selectObjReturn = dbHelp.Select(strSelectSql)
    _respon["ErrorInfo"]["ErrorCode"] = selectObjReturn["ErrorCode"]
    _respon["ErrorInfo"]["ErrorMsg"] = selectObjReturn["ErrorMsg"]
    _respon["IsError"] = selectObjReturn["IsError"]
    _respon["ReturnValue"] = selectObjReturn["ReturnValue"]
    if selectObjReturn["ReturnValue"]:
        _respon["paperTable"] = selectObjReturn["Value"]
        _respon["PartBScore"] = int(selectObjReturn["Value"][0]["PartBScore"])
    return _respon

# 试卷查询 - 分页查询
def _api_testpaper_view_page_all(_request):
    """
         API /api/testpaper.view.page.all

        功能：试卷查询 -- 分页查询
        编写：朱盼盼
        :param _request: 传入参数 = {"RequestBaseHeader":{"SeesionKey":"","TimeSpan":""},"Num_Now":1,"Num_Every":2,"SelectType":1,"TPCode":1}
        :param _request: 传入参数 = {"RequestBaseHeader":{"SeesionKey":"","TimeSpan":""},"Num_Now":1,"Num_Every":2,"SelectType":0}
        :param _request["Num_Now"]:当前页数
        :param _request["Num_Every"]:每页记录数
        :return: _respon 返回信息 = {"pageCount": 2, "CountNum": 3, "rTables": [{"Grade": 3, "Examinee": "gf", "DName": "UI设计", "TPCode": 3, "DateBuild": "2016-11-29"}, {"Grade": 77, "Examinee": "gf", "DName": "UI设计", "TPCode": 2, "DateBuild": "2016-11-29"}], "ReturnValue": true, "currentPage": 1, "RowNum": 2, "ErrorInfo": {"ErrorCode": 0, "ErrorMsg": ""}, "IsError": false}
        :param _respon["pageCount"]:传出的题目字典类型
        :param _respon["CountNum"]:总数
        :param _respon["rTables"]:记录数
                        :param _respon["Grade"]:得分
                        :param _respon["Examinee"]:面试人
                        :param _respon["DName"]:面试职位
                        :param _respon["TPCode"]:试卷编码
                        :param _respon["DateBuild"]:创建日期
        :param _respon["currentPage"]:当前页数
        :param _respon["RowNum"]:行数
        """
    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": "", "RowNum": "0","pageCount": "1", "currentPage": "1", "CountNum": "1"}
    # 1 查询一共有多少条记录
    if _request["SelectType"] == 0:
        strSqlGetAllRowNum = """
                           select count(*) num
                           from testpapera T
                           where T.IsDelete=0

                          """
    else:
        if _request["SelectType"] == 1:  # 根据试卷编码查询
            strSqlGetAllRowNum = """
                       select count(*) num
                           from testpapera T
                           where T.IsDelete=0
                           AND T.TPCode= '""" + str(_request["TPCode"]) + """'
                   """
        else:
            pass
    csNumAllRowNumObj = dbHelp.Select(strSqlGetAllRowNum)
    _respon["IsError"] = csNumAllRowNumObj["IsError"]
    _respon["ErrorInfo"]["ErrorCode"] = csNumAllRowNumObj["ErrorCode"]
    _respon["ErrorInfo"]["ErrorMsg"] = csNumAllRowNumObj["ErrorMsg"]
    _respon["ReturnValue"] = csNumAllRowNumObj["ReturnValue"]
    _respon["CountNum"] = csNumAllRowNumObj["Value"][0]["num"]
    if csNumAllRowNumObj["ReturnValue"] == False:
        pass  # 不执行下去了
    else:
        objReturnPag = complete.FY_Paging(_request["Num_Now"], int(csNumAllRowNumObj["Value"][0]["num"]),
                                          _request["Num_Every"])

        number_BeginGetRowNumer = objReturnPag["number_BeginGetRowNumer"]
        number_EveryPageHadNum = objReturnPag["number_EveryPageHadNum"]
        number_AllPageNumer = objReturnPag["number_AllPageNumer"]
        number_PageNumer_Now = objReturnPag["number_PageNumer_Now"]
        if _request["SelectType"] == 0:
            strSqlSelect = """
                 SELECT T.TPCode,DATE_FORMAT(T.DateBuild,'%Y-%m-%d') as DateBuild,T1.DName,T.Examinee,(T.PartAScore+T.PartBScore) AS Grade
                FROM testpapera T
                LEFT JOIN tb_class T1
                ON T1.MID = T.JobID
                where T.IsDelete=0
                AND T1.IsDelete=0
                ORDER BY T.TPCode DESC
                limit  """ + str(number_BeginGetRowNumer) + """ , """ + str(number_EveryPageHadNum) + """
                   """
        else:
            if _request["SelectType"] == 1:
                strSqlSelect = """
         SELECT T.TPCode,DATE_FORMAT(T.DateBuild,'%Y-%m-%d') as DateBuild,T1.DName,T.Examinee,(T.PartAScore+T.PartBScore) AS Grade
            FROM testpapera T
            LEFT JOIN tb_class T1
            ON T1.MID = T.JobID
            where T.IsDelete=0
            AND T1.IsDelete=0
			AND T.TPCode= '""" + str(_request["TPCode"]) + """'
           ORDER BY T.TPCode DESC
                            """
            else:
                pass
        selectObj = dbHelp.Select(strSqlSelect)
        _respon["IsError"] = selectObj["IsError"]
        _respon["ErrorInfo"]["ErrorCode"] = selectObj["ErrorCode"]
        _respon["ErrorInfo"]["ErrorMsg"] = selectObj["ErrorMsg"]
        _respon["ReturnValue"] = selectObj["ReturnValue"]

        if selectObj["ReturnValue"]:
            _respon["pageCount"] = number_AllPageNumer
            _respon["currentPage"] = number_PageNumer_Now
            _respon["RowNum"] = len(selectObj["Value"])
            _respon["rTables"] = selectObj["Value"]
        else:
            _respon["RowNum"] =0
    return _respon

# API 试卷查询 - 仅显示题目（打印试题、在线答题用）
def _api_testpaper_view_title(_request):
    """
     API /api/testpaper.view.title

    功能：试卷查询 -- 仅显示题目
    编写：朱盼盼
    :param _request: 传入参数 = {{"RequestBaseHeader":{"SeesionKey":"","TimeSpan":""},"TPCode":2}
    :param _request["TPCode"]:试卷编码

    :return: _respon 返回信息 = {"TBTypeNumView":
[{"ItemScore": 3,
	"answer": [{"AnswerText": "sdga", "OrderCode": "A", "AnswerCode": 369},
	{"AnswerText": "sadf", "OrderCode": "B", "AnswerCode": 370},
	{"AnswerText": "sdfjh", "OrderCode": "C", "AnswerCode": 371},
	{"AnswerText": "kjsdhfk", "OrderCode": "D", "AnswerCode": 372}], "ItemCode": 73, "ItemType": "单选", "ItemQuestion": "hahahahahah"},

{"ItemScore": 3,
	"answer": [
	{"AnswerText": "1", "OrderCode": "A", "AnswerCode": 289},
	{"AnswerText": "2", "OrderCode": "B", "AnswerCode": 290},
	{"AnswerText": "3", "OrderCode": "C", "AnswerCode": 291},
	{"AnswerText": "4", "OrderCode": "D", "AnswerCode": 292}], "ItemCode": 45, "ItemType": "单选", "ItemQuestion": "1"}
	"ItemCode": 74, "ItemType": "多选", "ItemQuestion": "asf"}], "ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "IsError": "", "ReturnValue": ""}
    :param _respon ["TBTypeNumView"]:传出的题目字典类型
                    :param _respon ["AnswerText"]:答案文本
                    :param _respon ["ItemType"]:题目类型
                    :param _respon ["OrderCode"]:记录数
                    :param _respon ["ItemCode"]:题目编码
                    :param _respon ["ItemQuestion"]:问题标题
                    :param _respon ["AnswerCode"]:答案编码
                    :param _respon ["ItemScore"]:分值
            :param _respon ["answer"]:答案集合

    """
    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": ""}
    sql01_select = """
      SELECT T1.ItemCode,T2.ItemType,T3.OrderCode,T3.AnswerText,T2.ItemQuestion,T3.AnswerCode,T1.ItemScore
                FROM testpaperb T1
                LEFT JOIN itema T2
                ON T1.ItemCode=T2.ItemCode
                LEFT JOIN itemb T3
                ON T2.ItemCode = T3.ItemCode
                WHERE T1.IsDelete=0
                AND T1.TPCode=   '""" + str(_request["TPCode"]) + """'
                AND T2.IsDelete=0
                AND (T3.IsDelete=0 OR T3.IsDelete IS NULL )
    """

    obj_01 = dbHelp.Select(sql01_select)

    list_01 = obj_01["Value"]

    # print type(list_01)
    # print list_01

    # list_02= []


    list_02 = []
    for x1 in list_01:
        # print x1["ItemCode"],x1["ItemType"],x1["ItemQuestion"],x1["ItemScore"]
        dicx = {}
        dicx["ItemCode"] = x1["ItemCode"]
        dicx["ItemType"] = x1["ItemType"]
        dicx["ItemQuestion"] = x1["ItemQuestion"]
        dicx["ItemScore"] = x1["ItemScore"]
        # dicx["answer"] = []
        # dicx["answer"].append(x1["AnswerCode"])
        # dicx["answer"].append(x1["OrderCode"])
        # dicx["answer"].append(x1["AnswerText"])

        dicx["answer"] = {"AnswerCode": "", "OrderCode": "", "AnswerText": "", "ItemCode": ""}
        dicx["answer"]["AnswerCode"] = (x1["AnswerCode"])
        dicx["answer"]["OrderCode"] = (x1["OrderCode"])
        dicx["answer"]["AnswerText"] = (x1["AnswerText"])
        dicx["answer"]["ItemCode"] = (x1["ItemCode"])
        # print dicx
        list_02.append(dicx)

    # print list_02

    list_03 = []

    for cs01 in list_02:
        # print cs01,type(cs01)
        # print cs01["ItemCode"]
        i = 0
        for cs02 in list_03:




            # print cs02["ItemCode"]
            if cs01["ItemCode"] == cs02["ItemCode"]:
                i = i + 1
                cs02["answer"].append(cs01["answer"])
                # cs02["answer"].setdefault(cs01["answer"])
            else:
                pass
        if i == 0:
            # print "add"
            list_03.append(
                {"ItemCode": cs01["ItemCode"], "ItemType": cs01["ItemType"], "ItemQuestion": cs01["ItemQuestion"],
                 "ItemScore": cs01["ItemScore"], "answer": [cs01["answer"]]})
        else:
            # print "update"
            pass
    _respon["TBTypeNumView"]=list_03
    return _respon

# API 试卷查询 - 显示题目和试卷信息
def _api_testpaper_view_title_print(_request):
    """
     API /api/testpaper.view.title.print

    功能：试卷查询 -- 显示题目和试卷信息
    编写：朱盼盼
    :param _request: 传入参数 = {{"RequestBaseHeader":{"SeesionKey":"","TimeSpan":""},"TPCode":2}
    :param _request["TPCode"]:试卷编码

    :return: _respon 返回信息 = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""},
"TBTypeNumView": [
	{"answer":
	[{"AnswerText": "1", "OrderCode": "A", "AnswerCode": 289},
	{"AnswerText": "2", "OrderCode": "B", "AnswerCode": 290},
	{"AnswerText": "3", "OrderCode": "C", "AnswerCode": 291},
	{"AnswerText": "4", "OrderCode": "D", "AnswerCode": 292}],
	"ItemCode": 45, "ItemType": "单选", "ItemScore": 3, "Examiner": "33", "Remarks": "33","DateBuild": "2016-12-12", "Examinee": "44", "ItemQuestion": "1"},

	{"answer": [
	{"AnswerText": "sdga", "OrderCode": "A", "AnswerCode": 369},
		{"AnswerText": "sadf", "OrderCode": "B", "AnswerCode": 370},
		{"AnswerText": "sdfjh", "OrderCode": "C", "AnswerCode": 371},
		{"AnswerText": "kjsdhfk", "OrderCode": "D", "AnswerCode": 372}],
		"ItemCode": 73, "ItemType": "单选", "ItemScore": 3, "Examiner": "33", "Remarks": "33","DateBuild": "2016-12-12", "Examinee": "44", "ItemQuestion": "hahahahahah"}], "IsError": "", "ReturnValue": ""}

    :param _respon["TBTypeNumView"]:传出的题目字典类型
    :param _respon["RowNum"]:记录数
                    :param _respon["ItemType"]:题目类型
                    :param _respon["ItemCode"]:题目编码
                    :param _respon["ItemQuestion"]:问题标题
                    :param _respon["ItemScore"]:分值
                    :param _respon["DateBuild"]:生成日期
                    :param _respon["TPCode"]:试卷编码
    :param _respon["Examiner"]:面试者
    :param _respon["Examinee"]:主考官
     :param _respon["Remarks"]:备注
    :param _respon["answer"]:答案字典

          :param _respon["AnswerCode"]:答案编码
          :param _respon["AnswerText"]:答案文本
          :param _respon["OrderCode"]:答案序号

    """
    _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": ""}
    sql01_select = """
            SELECT T1.ItemCode,
            T2.ItemType
            ,T3.OrderCode,
            T3.AnswerText,
            T2.ItemQuestion,
            T3.AnswerCode,
            T1.ItemScore,
            DATE_FORMAT(T4.DateBuild,'%Y-%m-%d') as DateBuild
            ,T4.TPCode
            ,T4.Examinee
			,T4.Examiner
			,T4.Remarks
            FROM testpaperb T1
            LEFT JOIN testpapera T4
            ON T1.TPCode=T4.TPCode
            LEFT JOIN itema T2
            ON T1.ItemCode=T2.ItemCode
            LEFT JOIN itemb T3
            ON T2.ItemCode = T3.ItemCode
            WHERE T1.IsDelete=0
            AND T1.TPCode=  '""" + str(_request["TPCode"]) + """'
            AND T1.IsDelete=0
            AND T2.IsDelete=0
            AND T4.IsDelete=0
            AND (T3.IsDelete=0 OR T3.IsDelete IS NULL )
         """
    obj_01 = dbHelp.Select(sql01_select)

    list_01 = obj_01["Value"]
    # print list_01
    # print type(list_01)
    # print list_01

    # list_02= []


    list_02 = []
    for x1 in list_01:
        # print x1["ItemCode"],x1["ItemType"],x1["ItemQuestion"],x1["ItemScore"]
        dicx = {}
        dicx["ItemCode"] = x1["ItemCode"]
        dicx["ItemType"] = x1["ItemType"]
        dicx["ItemQuestion"] = x1["ItemQuestion"]
        dicx["ItemScore"] = x1["ItemScore"]


        # dicx["answer"] = []
        # dicx["answer"].append(x1["AnswerCode"])
        # dicx["answer"].append(x1["OrderCode"])
        # dicx["answer"].append(x1["AnswerText"])

        dicx["answer"] = {"AnswerCode": "", "OrderCode": "", "AnswerText": "", "ItemCode": ""}
        dicx["answer"]["AnswerCode"] = (x1["AnswerCode"])
        dicx["answer"]["OrderCode"] = (x1["OrderCode"])
        dicx["answer"]["AnswerText"] = (x1["AnswerText"])
        dicx["answer"]["ItemCode"] = (x1["ItemCode"])
        # print dicx
        list_02.append(dicx)
    list_03 = []

    for cs01 in list_02:
        # print cs01,type(cs01)
        # print cs01["ItemCode"]
        i = 0
        for cs02 in list_03:

            # print cs02["ItemCode"]
            if cs01["ItemCode"] == cs02["ItemCode"]:
                i = i + 1
                cs02["answer"].append(cs01["answer"])
                # cs02["answer"].setdefault(cs01["answer"])
            else:
                pass
        if i == 0:
            # print "add"
            list_03.append(
                {"ItemCode": cs01["ItemCode"], "ItemType": cs01["ItemType"], "ItemQuestion": cs01["ItemQuestion"],
                 "ItemScore": cs01["ItemScore"], "answer": [cs01["answer"]]})
        else:
            pass
    sql04_select = """
       SELECT
        DATE_FORMAT(T4.DateBuild,'%Y-%m-%d') as DateBuild
        ,T4.TPCode
        ,T4.Examinee
    ,T4.Examiner
    ,T4.Remarks
        FROM testpapera T4
        WHERE T4.IsDelete=0
        AND T4.TPCode=   '""" + str(_request["TPCode"]) + """'
             """
    # print sql04_select
    obj_04 = dbHelp.Select(sql04_select)

    list_04 = obj_04["Value"]
    # list_05 = {}
    # for x4 in list_04:
    #     list_05["DateBuild"] = x4["DateBuild"]
    #     list_05["TPCode"] = x4["TPCode"]
    #     list_05["Examinee"] = x4["Examinee"]
    #     list_05["Examiner"] = x4["Examiner"]
    #     # print list_05
    #     list_03.append(list_05)
    # print list_03
    _respon["TPCode"] =obj_04["Value"][0]["TPCode"]
    _respon["DateBuild"] =obj_04["Value"][0]["DateBuild"]
    _respon["Examinee"] = obj_04["Value"][0]["Examinee"]
    _respon["Examiner"] = obj_04["Value"][0]["Examiner"]
    _respon["Remarks"] = obj_04["Value"][0]["Remarks"]
    _respon["TBTypeNumView"] = list_03
    return _respon

def _api_testpaper_delete(_request):
     """
         /api/testpaper.delete

          功能：试卷管理--删除
          编写：朱盼盼
          :param _request:传入参数 ={"RequestBaseHeader":{"SeesionKey":"","TimeSpan":""},"TPCode":2,"operationUserID":2}
          :param _request["TPCode"]:试卷编码
          :param _request["operationUserID"]:操作者ID
          :return:_request返回信息={"ErrorInfo": {"ErrorCode": 0, "ErrorMsg": ""}, "IsError": false, "ReturnValue": true}
          """
     _respon = {"ErrorInfo": {"ErrorCode": "0", "ErrorMsg": ""}, "ReturnValue": "", "IsError": ""}
     sqlDel = """
            UPDATE testpapera T1
            INNER JOIN
            testpaperb T2
            ON T1.TPCode=T2.TPCode
            SET
             T1.update_user='""" + str(_request["operationUserID"]) + """',
             T1.update_time=DATE_FORMAT(now(),'%Y-%m-%d %H:%i:%s'),
             T2.update_user='""" + str(_request["operationUserID"]) + """',
             T2.update_time=DATE_FORMAT(now(),'%Y-%m-%d %H:%i:%s'),
             T1.IsDelete=1,
             T2.IsDelete=1
            where T1.TPCode='""" + str(_request["TPCode"]) + """'
        """
     objReturn = dbHelp.Exec(sqlDel)
     _respon["ErrorInfo"]["ErrorCode"] = objReturn["ErrorCode"]
     _respon["ErrorInfo"]["ErrorMsg"] = objReturn["ErrorMsg"]
     _respon["IsError"] = objReturn["IsError"]
     _respon["ReturnValue"] = objReturn["ReturnValue"]
     return _respon
